

#include "array+trim.h"


void array_trim_reset(array_trim_data_t* trim)
{
    trim->stage = ARRAY_TRIM_STAGE_WAIT; 
}

void array_trim_data_enqueue_byte(array_trim_data_t* trim, uint8_t data)
{
    switch( trim->stage )
    {
        case ARRAY_TRIM_STAGE_WAIT:
            if( data > 0 ) 
            {
                trim->param.u8[0] = data;
                trim->len = 1;
                trim->count_of_invalid = 0; 
                trim->stage = ARRAY_TRIM_STAGE_BEGIN;
            }
            break;
        case ARRAY_TRIM_STAGE_BEGIN:
            trim->param.u8[ trim->len ++ ] = data;
            if( data > 0 )
            {
                trim->count_of_invalid = 0;
            }
            else 
            {
                trim->count_of_invalid ++;
            }
            if( trim->len >= BUFFER_SIZE ) 
            {
                trim->stage = ARRAY_TRIM_STAGE_FULL; 

                trim->len -= trim->count_of_invalid;
            }
            else if( trim->count_of_invalid > 3 )
            {
                trim->len -= trim->count_of_invalid;
                trim->stage = ARRAY_TRIM_STAGE_FULL; 
            }
            break;
        default:
            trim->stage = ARRAY_TRIM_STAGE_WAIT; 
            break;
    }
}

void array_data_trim_last_empty(array_trim_data_t* toTrim)
{
    if( toTrim->len == 0 )
    {
        return;
    }
    int idx = toTrim->len - 1;
    while( toTrim->param.u8[idx] == 0)
    {
        idx --;
    }
    
    toTrim->len = idx + 1;
}
